package com.msf.tutorial.java8.chapter1;

import com.msf.tutorial.java8.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 第三种状态：使用策略模式，将实现滞后
 *
 * 优点：
 * 1、行为参数化，filterApples方法的行为取决于你通过 AppleFilter 对象传递的代码。
 * 换句话说，你把filterApples方法的行为参数化了！
 * 2、多种行为一个参数
 *
 * 缺点：
 * 需要创建大量的策略类，而且每个格式都差不多
 */
public class Step3 {

    interface AppleFilter {
        boolean test(Apple apple);
    }

    static class GreenAppleFilter implements AppleFilter {
        @Override
        public boolean test(Apple apple) {
            return "green".equals(apple.getColor());
        }
    }

    static class RedAppleFilter implements AppleFilter {
        @Override
        public boolean test(Apple apple) {
            return "red".equals(apple.getColor());
        }
    }

    static class GreenAnd150gAppleFilter implements AppleFilter {
        @Override
        public boolean test(Apple apple) {
            return "green".equals(apple.getColor()) && apple.getWeight() > 150;
        }
    }

    /**
     * 把颜色作为参数
     */
    public static List<Apple> filterApples(List<Apple> inventory, AppleFilter filter) {
        List<Apple> result = new ArrayList<>();
        for (Apple apple: inventory) {
            if ( filter.test(apple) ) {
                result.add(apple);
            }
        }
        return result;
    }

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(
            new Apple(1L, "red", 1D),
            new Apple(2L, "red", 2D),
            new Apple(3L, "green", null),
            new Apple(1L, "green", 3D)
        );

        List<Apple> greenApples = filterApples(list, new GreenAppleFilter());
        List<Apple> redApples = filterApples(list, new RedAppleFilter());

        System.out.println(greenApples);
        System.out.println(redApples);

    }

}
